$(function() {

	var password = $( "#password" ),
		allFields = $( [] ).add( password ),
		tips = $( ".validateTips" );

	function updateTips( t ) {
		tips
			.text( t )
			.addClass( "ui-state-highlight" );
		setTimeout(function() {
			tips.removeClass( "ui-state-highlight", 1500 );
		}, 500 );
	}

	function checkLength( o, n, min, max ) {
		if ( o.val().length > max || o.val().length < min ) {
			o.addClass( "ui-state-error" );
			updateTips( "Length of " + n + " must be between " +
				min + " and " + max + "." );
			return false;
		} else {
			return true;
		}
	}

	function checkRegexp( o, regexp, n ) {
		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass( "ui-state-error" );
			updateTips( n );
			return false;
		} else {
			return true;
		}
	}

	function checkLogin(password) {
		$.ajaxSetup({async:false});
    	$.post("ajax/check_login.php", {password: password.val()}, function(data){
			if(data == 'true'){
				login = true;
			} else {
    			login = false;
			}
	    });
    	$.ajaxSetup({async:true});
    	return login;
	}
	
	$( "#dialog-form" ).dialog({			
		autoOpen: false,
		height: 300,
		width: 350,
		modal: true,
		buttons: {
			"Inloggen": function() {
				
				var bValid = true;
				allFields.removeClass( "ui-state-error" );

				bValid = bValid && checkLength( password, "password", 5, 16 );
				bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Wachtwoord bestaat alleen uit cijfers en letters" );

				if ( bValid ) {
					if( checkLogin( password ) ) {
						URL = $('input[name=URL]').val();
						window.location = URL + 'saldo';
					} else {
						updateTips('U heeft een verkeerd wachtwoord ingevult');
					}
				}
			},
			"Sluiten": function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			allFields.val( "" ).removeClass( "ui-state-error" );
		}
	});
	
	$( "#info-form" ).dialog({			
		autoOpen: false,
		height: 300,
		width: 350,
		modal: true,
		buttons: {
			"Sluiten": function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			allFields.val( "" ).removeClass( "ui-state-error" );
		}
	});


});
